﻿using System.Data.SqlClient;

namespace DesoutterTest
{
    class ResultHandler
    {
        /// <summary>
        /// 通过ID获取RESULT某行数据
        /// SELECT RES_ID id,  RES_ResultNumber resultnumber, RES_VIN vin,  RES_DateTime datetime   FROM RESULT R WHERE R.RES_ID = id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Result FetchResultByID(int id)
        {
            string sqlQuery = $"{Context.ResultBasicSQL} WHERE R.RES_ID = {id};";
            // sqlQuery = $"SELECT TOP (1000) [CRV_CurveID],[CRV_ResultID],[CRV_PointDuration],[CRV_PointCount],[CRV_CurveType],[CRV_TorqueThreshold],[CRV_BlobFormat],[CRV_Points] FROM [newcvinet].[dbo].[CURVE] WHERE CRV_CurveID={id}";
            using (SqlConnection conn = new SqlConnection(Context.GetConnectionString()))
            {
                conn.Open();
                using (SqlCommand command = new SqlCommand(sqlQuery, conn))
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    Result result = new Result();
                    if (reader.Read())
                    {
                        result.Id = reader.GetInt32(reader.GetOrdinal("id"));
                        result.ResultNumber = reader.GetInt64(reader.GetOrdinal("resultnumber"));
                        result.Vin = reader.GetString(reader.GetOrdinal("vin"));
                        result.DateTime = reader.GetDateTime(reader.GetOrdinal("dateTime"));
                    }
                    return result;
                }
            }
        }

        /// <summary>
        /// 加载通过Result对象获取外键对应的CURVE对象的数据库原始值
        /// </summary>
        /// <param name="result">加载过CURVE数据的Result对象</param>
        /// <returns></returns>
        public Result LazyLoadCurveInResult(Result result)
        {
            if (result != null && result.Id > 0)
            {
                CurveHandler curveHandler = new CurveHandler();
                result.Curve = curveHandler.FetchCurveByResultID(result.Id);
            }
            return result;
        }
    }
}
